package com.example.javamaday.reentrantlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock学习（二）
 * <p>
 * 使用ReentrantLock可以替代synchronized.同时ReentrantLock又比synchronized灵活，因为其可以使用
 * tryLock进行尝试锁定，当无法锁定的时候或者在指定时间内无法锁定的时候，线程可以决定是否继续等待。
 * <p>
 * <p>
 * 注意：必须要注意手动释放锁的逻辑，尤其是异常处理的时候。
 */
public class ReentrantLock2 {
    private Lock lock = new ReentrantLock();

    private void fun1() {
        lock.lock();
        try {
            for (int i = 0; i < 10; i++) {
                Thread.sleep(1000);
                System.out.println(i);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    private void fun2_tryLock() {
        boolean isGetLock = lock.tryLock();
        if (isGetLock) {
            System.out.println("Get Lock，Fun2 Run.");
            lock.unlock();
        } else {
            System.out.println("No Lock, No Wait.");
        }
    }

    private void fun2_tryLock_withTime() {
        boolean isGetLock = false;
        try {
            isGetLock = lock.tryLock(5, TimeUnit.SECONDS);
            lock.lockInterruptibly();
            System.out.println("fun2 run.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (isGetLock) {
                lock.unlock();
            } else {
                System.out.println("No Lock, No Wait.");
            }
        }

        lock.unlock();
    }

    public static void main(String[] args) {
        ReentrantLock2 reentrantLock2 = new ReentrantLock2();
        new Thread(reentrantLock2::fun1).start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // new Thread(reentrantLock2::fun2_tryLock).start();
        new Thread(reentrantLock2::fun2_tryLock_withTime).start();
    }
}
